{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "24dd70b4",
   "metadata": {},
   "source": [
    "# 1. 输入输出\n",
    "\n",
    "## 1.1 输入\n",
    "\n",
    "`eval(input())`：eval()可以去除输入的字符串的引号，输入数字时比较方便\n",
    "\n",
    "<font color='blue'>**当输入要求在一行中输入（用逗号分隔）时，用eval函数很方便。因为eval()会将input()返回的字符串的引号去除，并转化为元组，后续可以直接用元组操作。**</font>\n",
    "\n",
    "`x, y = map(int, input().split(\",\"))`：用map函数可以把多个输入映射成指定数据结构\n",
    "\n",
    "## 1.2 输出\n",
    "\n",
    "```python\n",
    "print(\"{:.2f}\".format(num)) # 保留两位小数\n",
    "print(\"{:<4}\".format(num)) # 左对齐，4位\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c89f73a9",
   "metadata": {},
   "source": [
    "# 2. 字符串\n",
    "\n",
    "## 2.1 内置函数和方法\n",
    "\n",
    "| 序号 | 方法及描述                                                   |\n",
    "| :--- | :----------------------------------------------------------- |\n",
    "| 1    | [capitalize()](https://www.runoob.com/python3/python3-string-capitalize.html) 将字符串的第一个字符转换为大写 |\n",
    "| 2    | [center(width, fillchar)](https://www.runoob.com/python3/python3-string-center.html)返回一个指定的宽度 width 居中的字符串，fillchar 为填充的字符，默认为空格。 |\n",
    "| 3    | [count(str, beg= 0,end=len(string))](https://www.runoob.com/python3/python3-string-count.html) 返回 str 在 string 里面出现的次数，如果 beg 或者 end 指定则返回指定范围内 str 出现的次数 |\n",
    "| 4    | [bytes.decode(encoding=\"utf-8\", errors=\"strict\")](https://www.runoob.com/python3/python3-string-decode.html) Python3 中没有 decode 方法，但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象，这个 bytes 对象可以由 str.encode() 来编码返回。 |\n",
    "| 5    | [encode(encoding='UTF-8',errors='strict')](https://www.runoob.com/python3/python3-string-encode.html) 以 encoding 指定的编码格式编码字符串，如果出错默认报一个ValueError 的异常，除非 errors 指定的是'ignore'或者'replace' |\n",
    "| 6    | [endswith(suffix, beg=0, end=len(string))](https://www.runoob.com/python3/python3-string-endswith.html) 检查字符串是否以 suffix 结束，如果 beg 或者 end 指定则检查指定的范围内是否以 suffix 结束，如果是，返回 True,否则返回 False。 |\n",
    "| 7    | [expandtabs(tabsize=8)](https://www.runoob.com/python3/python3-string-expandtabs.html) 把字符串 string 中的 tab 符号转为空格，tab 符号默认的空格数是 8 。 |\n",
    "| 8    | [find(str, beg=0, end=len(string))](https://www.runoob.com/python3/python3-string-find.html) 检测 str 是否包含在字符串中，如果指定范围 beg 和 end ，则检查是否包含在指定范围内，如果包含返回开始的索引值，否则返回-1 |\n",
    "| 9    | [index(str, beg=0, end=len(string))](https://www.runoob.com/python3/python3-string-index.html) 跟find()方法一样，只不过如果str不在字符串中会报一个异常。 |\n",
    "| 10   | [isalnum()](https://www.runoob.com/python3/python3-string-isalnum.html) 检查字符串是否由字母和数字组成，即字符串中的所有字符都是字母或数字。如果字符串至少有一个字符，并且所有字符都是字母或数字，则返回 True；否则返回 False。 |\n",
    "| 11   | [isalpha()](https://www.runoob.com/python3/python3-string-isalpha.html) 如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False |\n",
    "| 12   | [isdigit()](https://www.runoob.com/python3/python3-string-isdigit.html) 如果字符串只包含数字则返回 True 否则返回 False.. |\n",
    "| 13   | [islower()](https://www.runoob.com/python3/python3-string-islower.html) 如果字符串中包含至少一个区分大小写的字符，并且所有这些(区分大小写的)字符都是小写，则返回 True，否则返回 False |\n",
    "| 14   | [isnumeric()](https://www.runoob.com/python3/python3-string-isnumeric.html) 如果字符串中只包含数字字符，则返回 True，否则返回 False |\n",
    "| 15   | [isspace()](https://www.runoob.com/python3/python3-string-isspace.html) 如果字符串中只包含空白，则返回 True，否则返回 False. |\n",
    "| 16   | [istitle()](https://www.runoob.com/python3/python3-string-istitle.html) 如果字符串是标题化的(见 title())则返回 True，否则返回 False |\n",
    "| 17   | [isupper()](https://www.runoob.com/python3/python3-string-isupper.html) 如果字符串中包含至少一个区分大小写的字符，并且所有这些(区分大小写的)字符都是大写，则返回 True，否则返回 False |\n",
    "| 18   | [join(seq)](https://www.runoob.com/python3/python3-string-join.html) 以指定字符串作为分隔符，将 seq 中所有的元素(的字符串表示)合并为一个新的字符串 |\n",
    "| 19   | [len(string)](https://www.runoob.com/python3/python3-string-len.html) 返回字符串长度 |\n",
    "| 20   | [ljust(width[, fillchar\\])](https://www.runoob.com/python3/python3-string-ljust.html) 返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串，fillchar 默认为空格。 |\n",
    "| 21   | [lower()](https://www.runoob.com/python3/python3-string-lower.html) 转换字符串中所有大写字符为小写. |\n",
    "| 22   | [lstrip()](https://www.runoob.com/python3/python3-string-lstrip.html) 截掉字符串左边的空格或指定字符。 |\n",
    "| 23   | [maketrans()](https://www.runoob.com/python3/python3-string-maketrans.html) 创建字符映射的转换表，对于接受两个参数的最简单的调用方式，第一个参数是字符串，表示需要转换的字符，第二个参数也是字符串表示转换的目标。 |\n",
    "| 24   | [max(str)](https://www.runoob.com/python3/python3-string-max.html) 返回字符串 str 中最大的字母。 |\n",
    "| 25   | [min(str)](https://www.runoob.com/python3/python3-string-min.html) 返回字符串 str 中最小的字母。 |\n",
    "| 26   | [replace(old, new [, max\\])](https://www.runoob.com/python3/python3-string-replace.html) 把 将字符串中的 old 替换成 new,如果 max 指定，则替换不超过 max 次。 |\n",
    "| 27   | [rfind(str, beg=0,end=len(string))](https://www.runoob.com/python3/python3-string-rfind.html) 类似于 find()函数，不过是从右边开始查找. |\n",
    "| 28   | [rindex( str, beg=0, end=len(string))](https://www.runoob.com/python3/python3-string-rindex.html) 类似于 index()，不过是从右边开始. |\n",
    "| 29   | [rjust(width,[, fillchar\\])](https://www.runoob.com/python3/python3-string-rjust.html) 返回一个原字符串右对齐,并使用fillchar(默认空格）填充至长度 width 的新字符串 |\n",
    "| 30   | [rstrip()](https://www.runoob.com/python3/python3-string-rstrip.html) 删除字符串末尾的空格或指定字符。 |\n",
    "| 31   | [split(str=\"\", num=string.count(str))](https://www.runoob.com/python3/python3-string-split.html) 以 str 为分隔符截取字符串，如果 num 有指定值，则仅截取 num+1 个子字符串 |\n",
    "| 32   | [splitlines([keepends\\])](https://www.runoob.com/python3/python3-string-splitlines.html) 按照行('\\r', '\\r\\n', \\n')分隔，返回一个包含各行作为元素的列表，如果参数 keepends 为 False，不包含换行符，如果为 True，则保留换行符。 |\n",
    "| 33   | [startswith(substr, beg=0,end=len(string))](https://www.runoob.com/python3/python3-string-startswith.html) 检查字符串是否是以指定子字符串 substr 开头，是则返回 True，否则返回 False。如果beg 和 end 指定值，则在指定范围内检查。 |\n",
    "| 34   | [strip([chars\\])](https://www.runoob.com/python3/python3-string-strip.html) 在字符串上执行 lstrip()和 rstrip() |\n",
    "| 35   | [swapcase()](https://www.runoob.com/python3/python3-string-swapcase.html) 将字符串中大写转换为小写，小写转换为大写 |\n",
    "| 36   | [title()](https://www.runoob.com/python3/python3-string-title.html) 返回\"标题化\"的字符串,就是说所有单词都是以大写开始，其余字母均为小写(见 istitle()) |\n",
    "| 37   | [translate(table, deletechars=\"\")](https://www.runoob.com/python3/python3-string-translate.html) 根据 table 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中 |\n",
    "| 38   | [upper()](https://www.runoob.com/python3/python3-string-upper.html) 转换字符串中的小写字母为大写 |\n",
    "| 39   | [zfill (width)](https://www.runoob.com/python3/python3-string-zfill.html) 返回长度为 width 的字符串，原字符串右对齐，前面填充0 |\n",
    "| 40   | [isdecimal()](https://www.runoob.com/python3/python3-string-isdecimal.html) 检查字符串是否只包含十进制字符，如果是返回 true，否则返回 false。 |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bdea6ddf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 几个比较常用的函数\n",
    "str = \"1112223334445554433221\"\n",
    "\n",
    "str.count(\"1\")\n",
    "str.startswith(\"1\")\n",
    "str.endswith(\"1\")\n",
    "str.index(\"2\") # 从左开始查找给定字符，返回索引值\n",
    "str.strip(\"1\") # 删除两端的给定字符\n",
    "str.lower()\n",
    "str.upper()\n",
    "str.strip(\"\\t\")\n",
    "','.join(str)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80750715",
   "metadata": {},
   "source": [
    "## 2.2 索引与切片\n",
    "\n",
    "![字符串索引](https://static.jyshare.com/wp-content/uploads/123456-20200923-1.svg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4f510e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 字符串切片：双冒号\n",
    "# 语法为str[start:end:step]\n",
    "\n",
    "str = 'abcdefghijklmnopqrstuvwxyz'\n",
    "str[::4]  # 每隔4个字符提取一个字符\n",
    "str[3::4]  # 从第4个字符开始，每隔4个字符提取一个字符\n",
    "str[3:10:2]  # 从第4个字符到第10个字符，每隔2个字符提取一个字符\n",
    "str[-1] # 最后一个字母\n",
    "str[-3:-1] # 倒数第3、2个字母，不包括最后一个（因为左闭右开）\n",
    "str[::-1] # 倒序输出"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3760bbc3",
   "metadata": {},
   "source": [
    "## 2.3 ASCII码\n",
    "\n",
    "- `chr(num)`\n",
    "- `ord(char)`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5c6715d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 练习4-字符串\n",
    "# 4. 字符串加密\n",
    "# 注意字母循环转换\n",
    "\n",
    "s = input()\n",
    "\n",
    "# 用ASCII码进行转换\n",
    "# ord() 函数返回字符的 ASCII 数值\n",
    "# chr() 函数将 ASCII 数值转换为字符\n",
    "def convert(s):\n",
    "    s_new = ''  # 用于存储转换后的字符串\n",
    "    for char in s:\n",
    "        if char.isupper(): # 大写字母\n",
    "            if char <= 'V':\n",
    "                char = chr(ord(char) + 5)\n",
    "            else:\n",
    "                char = chr(ord(char) - 21)\n",
    "            s_new += char\n",
    "        elif char.islower(): # 小写字母\n",
    "            if char <= 'x':\n",
    "                char = chr(ord(char) + 3)\n",
    "            else:\n",
    "                char = chr(ord(char) - 23)\n",
    "            s_new += char\n",
    "        else:\n",
    "            s_new += char\n",
    "    return s_new\n",
    "\n",
    "print(convert(s))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1068cdec",
   "metadata": {},
   "source": [
    "# 3. 列表与元组"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffe52ebf",
   "metadata": {},
   "source": [
    "# 4. 集合与字典\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3610d77f",
   "metadata": {},
   "source": [
    "# 5. 函数\n",
    "\n",
    "## 5.1 隐函数\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af3d5e03",
   "metadata": {},
   "source": [
    "## 5.2 解包\n",
    "\n",
    "https://www.cnblogs.com/hls-code/p/15227567.html\n",
    "\n",
    "解包在英文里叫做 Unpacking，就是将容器里面的元素逐个取出来（防杠精：此处描述并不严谨，因为容器中的元素并没有发生改变）放在其它地方。\n",
    "除了列表对象可以解包之外，任何可迭代对象都支持解包；可迭代对象包括元组、字典、集合、字符串、生成器等实现了__next__方法的一切对象。\n",
    "\n",
    "解包就是把一个容器拆开、分解，在Python中的解包是自动完成的。\n",
    "\n",
    "**变量数量 = 元素数量，会进行逐一赋值**\n",
    "\n",
    "**在 Python 中，交换两个变量非常方便，本质上也是自动解包过程**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e033bbb9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 基础的解包\n",
    "\n",
    "## 列表与元组\n",
    "a,b,c = [1,2,3]\n",
    "a,b,c = (1,2,3)\n",
    "\n",
    "## 字典\n",
    "a,b,c = {\"a\":1,\"b\":2,\"c\":3} # 注意！字典解包后只能取出key值，value丢失\n",
    "\n",
    "## 字符串\n",
    "a,b,c = \"abc\"\n",
    "\n",
    "## 生成器\n",
    "a,b,c = (x + 1 for x in range(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f46ec13",
   "metadata": {},
   "source": [
    "**python3中，支持更高级的解包操作，用星号操作使得等号左边的变量个数可以少于右边迭代对象中元素的个数**\n",
    "（python2中，如果等号左边变量的个数不等于右边元素的个数，不允许赋值）\n",
    "\n",
    "这种语法就是在某个变量面前加一个星号，而且这个星号可以放在任意变量，每个变量都分配一个元素后，剩下的元素都分配给这个带星号的变量。\n",
    "\n",
    "注：**符号作用的对象是字典对象，它会自动解包成关键字参数 key=value 的格式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e185746",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 7. 构造整数\n",
    "#定义lambda函数getLastBit返回一个数的个位数\n",
    "getLastBit = lambda num: num % 10\n",
    "\n",
    "#定义一个可变参数的函数makeNumber，求任意个整数的个位数构成的一个新整数\n",
    "def makeNumber(*a):\n",
    "    # print(a)\n",
    "    s = \"\"\n",
    "    for num in a:\n",
    "        s += str(getLastBit(num))\n",
    "    return int(s) # 这里要转化为int，这样对于s=\"000\"的情况，可以转化为s=0\n",
    "\n",
    "#输入一组逗号分隔的数，截取个位数构成的新整数。\n",
    "# t = eval(input())\n",
    "t = map(int, input().split(\",\"))\n",
    "print(\"新整数是{}\".format(makeNumber(*t)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9452a4e",
   "metadata": {},
   "outputs": [],
   "source": [
    "#定义lambda函数getLastBit返回一个数的个位数\n",
    "getLastBit = lambda num: num % 10\n",
    "\n",
    "#定义一个可变参数的函数makeNumber，求任意个整数的个位数构成的一个新整数\n",
    "def makeNumber(a, *b):\n",
    "    s = str(getLastBit(a))\n",
    "    for num in b:\n",
    "        s += str(getLastBit(num))\n",
    "    return int(s)\n",
    "\n",
    "#输入一组逗号分隔的数，截取个位数构成的新整数。\n",
    "t = eval(input())\n",
    "print(\"新整数是%d\" % makeNumber(*t)) # 将列表/元组中每个元素作为独立的单数传递\n",
    "# makeNumber(*t)会把t的每个元素分别传给a, *b，而不是把整个t作为一个参数传递\n",
    "# 如果直接写makeNumber(t)，那么a会接收到整个列表或元组，*b为空，导致结果不正确"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74d6d2ec",
   "metadata": {},
   "source": [
    "解包操作还可以很方便地拼接元组/列表/字典，例如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39d7737e",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [1, 2]\n",
    "b = [\"1\", \"2\"]\n",
    "print([*a, *b])\n",
    "# [1, 2, '1', '2']\n",
    "\n",
    "d1 = {\"a\":1, \"b\":2}\n",
    "d2 = {\"x\":9, \"y\":8}\n",
    "print(dict(**d1, **d2))\n",
    "#{'a': 1, 'b': 2, 'x': 9, 'y': 8}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c88a3e0",
   "metadata": {},
   "source": [
    "# 6. 几个常用算法\n",
    "\n",
    "## 6.1 判断素数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2718f7b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "def is_prime(num):\n",
    "    if num <= 1:\n",
    "        return False\n",
    "    for i in range(2, math.sqrt(num) + 1):\n",
    "        if num % i == 0:\n",
    "            return False\n",
    "    return True"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d63eb55",
   "metadata": {},
   "source": [
    "## 6.2 计算阶乘"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bdecb625",
   "metadata": {},
   "outputs": [],
   "source": [
    "def factorial(n):\n",
    "    rst = 1 # 要求n>0\n",
    "    for i in range(n + 1): # 注意这里要n+1\n",
    "        rst *= i\n",
    "    return rst"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
